package net.roobook.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import net.roobook.common.entity.RoobookConstant;
import net.roobook.common.entity.RoobookResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Roobook
 * @description 微服务全局拦截器拦截请求，实现了HandlerInterceptor的preHandle方法，该拦截器可以拦截所有Web请求
 * @date 2022/4/8
 */
public class RoobookServerProtectInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 从请求头中获取 Zuul Token
        String token = request.getHeader(RoobookConstant.ZUUL_TOKEN_HEADER);
        String zuulToken = new String(Base64Utils.encode(RoobookConstant.ZUUL_TOKEN_VALUE.getBytes()));
        // 校验 Zuul Token的正确性
        if (StringUtils.equals(zuulToken, token)) {
            return true;
        } else {
            RoobookResponse roobookResponse = new RoobookResponse();
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(JSONObject.toJSONString(roobookResponse.message("请通过网关获取资源")));
            return false;
        }
    }
}